package cn.liangjintang.webserver;
import java.io.File;
import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import cn.liangjintang.webserver.webserver.NanoHTTPD;

public class WebServer extends Service {
    final String TAG = "WebServer";
    NanoHTTPD nanoHTTPD;
    public int port;
    public File wwwroot;
    public static WebServer webServer;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    // 当服务第1次创建时调用该方法
    @Override
    public void onCreate()

    {

        Log.d(TAG, "onCreate");
        super.onCreate();

    }

    // 当服务销毁时调用该方法

    @Override
    public void onDestroy()

    {

        Log.d(TAG, "onDestroy");
        stop();
        super.onDestroy();

    }

    // 当开始服务时调用该方法
    // @Override
    // public void onStart(Intent intent, int startId) {
    // Log.d(TAG, "onStart");
    // start(intent);
    // webServer = WebServer.this;
    // super.onStart(intent, startId);
    // }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStart");
        start(intent);
        webServer = WebServer.this;
        int retVal = super.onStartCommand(intent, flags, startId);
        return retVal;
    }

    private final void start(Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            port = bundle.getInt("PORT");
            String path = bundle.getString("PATH");
            wwwroot = new File(path);
            nanoHTTPD = new NanoHTTPD(port, wwwroot);
            Log.i(TAG, "start server wwwroot:" + wwwroot.getAbsolutePath() + " port:" + port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private final void stop() {
        if (nanoHTTPD != null)
            nanoHTTPD.stop();
    }

}
